package cn.bitkit.tools.file;

import lombok.SneakyThrows;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

public class FileLimiter {
    public static final int BUFF_LENGTH = 1024;

    @SneakyThrows
    public static void write(InputStream in, OutputStream out, int limit){
        int read;
        int count = 0;
        long startTime = System.currentTimeMillis();
        byte[] buffer = new byte[BUFF_LENGTH];
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            count += read;
            if(count >= limit){
                long useTime = System.currentTimeMillis() - startTime;
                if(useTime < 1000){
                    TimeUnit.MILLISECONDS.sleep(1000 - useTime);
                }
                startTime = System.currentTimeMillis();
                count = 0;
            }
        }
        out.flush();
        out.close();
    }
}
